package com.wd.health.view.activity.mine;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.wd.health.R;
import com.wd.health.model.bean.MessageStatusBean;
import com.wd.health.utils.FileUtil;
import com.wd.health.utils.RecognizeService;
import com.wd.health.utils.RetrofitManager;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class BdyhkActivity extends AppCompatActivity {

    private ImageView img_back;
    private RelativeLayout rl_yhk;
    private ImageView img_shexiang03;
    private Button btn_banding;
    private static final int REQUEST_CODE_BANKCARD = 111;
    private boolean hasGotToken = false;
    private AlertDialog.Builder alertDialog;
    private String yhkhao;
    private String yhkfaxinghang;
    private String yhkleixing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bdyhk);
        alertDialog = new AlertDialog.Builder(this);
        initAccessTokenWithAkSk();
        initView();
    }

    private void initView() {
        img_back = findViewById(R.id.img_back);
        rl_yhk = findViewById(R.id.rl_yhk);
        img_shexiang03 = findViewById(R.id.img_shexiang03);
        btn_banding = findViewById(R.id.btn_banding);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        img_shexiang03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkTokenStatus()) {
                    return;
                }
                Intent intent = new Intent(BdyhkActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                startActivityForResult(intent, REQUEST_CODE_BANKCARD);
            }
        });
        btn_banding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BdYhk();
            }
        });
    }

    private void BdYhk() {
        RetrofitManager.getInstance().postYhkData(yhkhao, yhkfaxinghang, 1, new Observer<MessageStatusBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MessageStatusBean messageStatusBean) {
                if (messageStatusBean.getStatus().equals("0000")){
                    Toast.makeText(BdyhkActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "zGgXZaxbN4xNXMRjppBXhxy6", "5o6GEEZFgSPaWvkDOVtRADFSf9GGmH04");
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    private void infoPopText(final String result) {
        alertText("", result);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 识别成功回调，银行卡识别
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            RecognizeService.recBankCard(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            yhkhao = result.substring(3, 22);
                            yhkleixing = result.substring(26, 31);
                            yhkfaxinghang = result.substring(35, 42);
                            infoPopText(result);
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance(this).release();
    }
}